import nodeResolve from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import { emptyDir } from 'fs-extra'
import { builtinModules } from 'module'
import { defineConfig } from 'rollup'
import dts from 'rollup-plugin-dts'
import { terser } from 'rollup-plugin-terser'
import pkg from './package.json'

const external = [
  ...builtinModules,
  ...Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies }).map(
    p => new RegExp(`^${p.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')}($|\/)`)
  )
]

export default defineConfig([
  {
    external,
    input: {
      index: 'src/index.ts'
    },
    output: {
      dir: 'dist'
    },
    plugins: [
      nodeResolve(),
      dts(),
      {
        name: 'extra',
        renderStart({ dir }) {
          if (dir && !this.meta.watchMode) {
            return emptyDir(dir)
          }
        }
      }
    ]
  },
  {
    external,
    input: {
      index: 'src/index.ts',
      rollup: 'src/rollup/index.ts',
      vite: 'src/vite/index.ts',
      esbuild: 'src/esbuild/index.ts',
      webpack: 'src/webpack/index.ts',
      'webpack/loaders/transform': 'src/webpack/loaders/transform.ts',
      'webpack/loaders/loadInfo': 'src/webpack/loaders/loadInfo.ts'
    },
    output: {
      dir: 'dist',
      format: 'cjs',
      entryFileNames: '[name].js',
      chunkFileNames: 'chunk-[hash].js',
      hoistTransitiveImports: false,
      sourcemap: true,
      compact: true,
      freeze: false,
      sourcemapExcludeSources: true,
      generatedCode: {
        preset: 'es2015',
        constBindings: true
      }
    },
    plugins: [nodeResolve(), typescript(), terser({ keep_fnames: /^[a-zA-Z]/, keep_classnames: true })]
  },
  {
    input: {
      shims__filename: 'src/shims__filename.ts'
    },
    output: {
      dir: 'dist',
      format: 'iife',
      entryFileNames: '[name].js',
      generatedCode: {
        preset: 'es2015',
        constBindings: true
      }
    },
    plugins: [nodeResolve(), typescript(), terser({ keep_fnames: /^[a-zA-Z]/, keep_classnames: true })]
  },
  {
    input: {
      shims: 'src/shims.ts'
    },
    output: {
      dir: 'dist',
      format: 'esm',
      entryFileNames: '[name].mjs',
      generatedCode: {
        preset: 'es2015',
        constBindings: true
      }
    },
    plugins: [nodeResolve(), typescript(), terser({ keep_fnames: /^[a-zA-Z]/, keep_classnames: true })]
  }
])
